//
//  OPMainOptionalController.m
//  OnePiece
//
//  Created by lanou on 15/10/27.
//  Copyright © 2015年 wsy. All rights reserved.
//

#import "OPMainOptionalController.h"
#import "OPRequesterManager.h"
#import "FMDatabase.h"

#import "OPMainOptionalModel.h"
#import "MainThemeModel.h"
#import "MainThemeCell.h"
#import "MainEuropeModel.h"
#import "MainEuropeCell.h"

#import "OPCountryController.h"
#import "OPThemeController.h"
#import "ThemeDetailController.h"

#import "ParitiesController.h"


#import <UIImageView+WebCache.h>
@interface OPMainOptionalController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *topCollectionView;
@property (nonatomic, strong) UICollectionView *bottomCollectionView;
@property (nonatomic, strong) UIScrollView *mainScr;

@property (nonatomic, strong) FMDatabase *dataBase;

@property (nonatomic, strong) NSMutableArray *europeDataArray;
@property (nonatomic, strong) NSMutableArray *themeDataArray;

@property (nonatomic, strong) MainEuropeModel *mainEuropeModel;
@property (nonatomic, strong) MainThemeModel *mainThemeModel;

@property (nonatomic, strong) UILabel *europeNameLabel;
@property (nonatomic, strong) UIButton *TtitleButton;
@property (nonatomic, strong) UILabel *TStitleLabel;

@property (nonatomic, copy) NSString *monthUrl;
@property (nonatomic, copy) NSString *themeUrl;

@property (nonatomic, strong) OPThemeController *TC;

@end

@implementation OPMainOptionalController




- (NSMutableArray *)europeDataArray
{
    if (_europeDataArray == nil) {
        _europeDataArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _europeDataArray;
}

- (NSMutableArray *)themeDataArray
{
    if (_themeDataArray == nil) {
        _themeDataArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _themeDataArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor colorWithRed:0.871 green:0.906 blue:0.949 alpha:1.0];
//    self.titleLable.text = @"去哪";
    
    
    _mainScr = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT- 69)];
    _mainScr.contentSize = CGSizeMake(SCREEN_WIDTH, (SCREEN_WIDTH-60)/3 + 360 + (SCREEN_WIDTH-90)*2);
    [self.view addSubview:_mainScr];
    _mainScr.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestUpData];
    }];

    [self configureTwoPartsTitle];
    [self configureTopCollectionView];
    [self configureBottomCollectionView];
    
    [_topCollectionView registerClass:[MainEuropeCell class] forCellWithReuseIdentifier:@"topCollection"];
    [_bottomCollectionView registerClass:[MainThemeCell class] forCellWithReuseIdentifier:@"bottomCollection"];
    [self requestUpData];
    [self requestDownData];
    [self keepEuropeData];
    [self keepThemeData];
}

- (void)keepEuropeData
{
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(9, 1, 1.).lastObject stringByAppendingPathComponent:@"OnePiece.db"];
    _dataBase = [FMDatabase databaseWithPath:filePath];
    NSLog(@"%@---------------------------------------------------",filePath);
    if ([_dataBase open]) {
        NSLog(@"-------打开MAINEUROPE数据库成功--------");

        [_dataBase executeUpdate:@"CREATE TABLE MAINEROUP (cover_s text, cover_route_map_cover text, name text, countryId text, visited_count integer, wish_to_go_count integer)"];
    }else{
        NSLog(@"=======打开MAINEUROPE数据库失败========");

    }
    FMResultSet *MainEurope = [_dataBase executeQueryWithFormat:@"SELecT * FROM MAINEROUP"];
    while ([MainEurope next]) {
        MainEuropeModel *model = [[MainEuropeModel alloc]init];
        
         model.cover_s = [MainEurope stringForColumn:@"cover_s"];
         model.cover_route_map_cover = [MainEurope stringForColumn:@"cover_route_map_cover"];
         model.name = [MainEurope stringForColumn:@"name"];
         model.countryId = [MainEurope stringForColumn:@"countriId"];
         model.visited_count = [MainEurope intForColumn:@"visited_count"];
         model.wish_to_go_count = [MainEurope intForColumn:@"wish_to_go_count"];
        [self.europeDataArray addObject:model];
        
    }
    [MainEurope close];
}

- (void)keepThemeData
{
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(9, 1, 1).lastObject stringByAppendingPathComponent:@"OnePiece.db"];
    _dataBase = [FMDatabase databaseWithPath:filePath];
    if ([_dataBase open]) {
        [_dataBase executeUpdate:@"create table MAINTHEME(img_url text, jump_url text, sub_title text, title text)"];
    }else{              NSLog(@"------打开MAINTHEME数据库失败-----");
    }
    FMResultSet *mainTheme = [_dataBase executeQueryWithFormat:@"select * from MAINTHEME"];
    while ([mainTheme next]) {
        MainThemeModel *model = [[MainThemeModel alloc]init];
        model.img_url = [mainTheme stringForColumn:@"img_url"];
        model.jump_url = [mainTheme stringForColumn:@"jump_url"];
        model.sub_title = [mainTheme stringForColumn:@"sub_title"];
        model.title = [mainTheme stringForColumn:@"title"];
        [self.themeDataArray addObject:model];
    }
    [mainTheme close];
}

- (void)configureTwoPartsTitle
{
    _europeNameLabel = [[UILabel alloc]initWithFrame: CGRectMake(0, (SCREEN_WIDTH-60)/3 + 95, SCREEN_WIDTH, 20)];
    _europeNameLabel.textAlignment = NSTextAlignmentCenter;
    _europeNameLabel.font = [UIFont systemFontOfSize:18];

    
    _TtitleButton= [UIButton buttonWithType:UIButtonTypeCustom];
    _TtitleButton.frame = CGRectMake(0, 10, SCREEN_WIDTH, 20);
    [_TtitleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_TtitleButton addTarget:self action:@selector(goToTheme) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *rightView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"iconfont-right"]];
    rightView.frame = CGRectMake(SCREEN_WIDTH-25, 1, 15, 18);
    [_TtitleButton addSubview:rightView];
    
    
    _TStitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, SCREEN_WIDTH, 20)];
    _TStitleLabel.textAlignment = NSTextAlignmentCenter;
    _TStitleLabel.font = [UIFont systemFontOfSize:10];
    _TStitleLabel.textColor = [UIColor grayColor];
    [self.mainScr addSubview:_europeNameLabel];
    [self.mainScr addSubview:_TtitleButton];
    [self.mainScr addSubview:_TStitleLabel];
}

- (void)configureTopCollectionView
{
    UICollectionViewFlowLayout *layOut = [[UICollectionViewFlowLayout alloc]init];
    layOut.itemSize = CGSizeMake((SCREEN_WIDTH-90)/2, (SCREEN_WIDTH-90)/2 + 30);
    layOut.minimumInteritemSpacing = 30;
    layOut.minimumLineSpacing = 10;
    layOut.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.navigationController.navigationBar.translucent = NO;

    _topCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, (SCREEN_WIDTH-60)/3 + 130, SCREEN_WIDTH, (SCREEN_WIDTH-90)*2 + 150) collectionViewLayout:layOut];
    _topCollectionView.backgroundColor = [UIColor whiteColor];
    _topCollectionView.dataSource = self;
    _topCollectionView.delegate = self;
    _topCollectionView.bounces = NO;
    _topCollectionView.scrollEnabled = NO;
    _topCollectionView.contentInset = UIEdgeInsetsMake(10, 30, 10, 30);
    [self.mainScr addSubview:_topCollectionView];
}

- (void)configureBottomCollectionView
{
    UICollectionViewFlowLayout *BlayOut = [[UICollectionViewFlowLayout alloc]init];
    BlayOut.itemSize = CGSizeMake((SCREEN_WIDTH-60)/3, (SCREEN_WIDTH-60)/3 + 30);
    BlayOut.minimumInteritemSpacing = 20;
    BlayOut.minimumLineSpacing = 10;
    BlayOut.scrollDirection = UICollectionViewScrollDirectionVertical;

    _bottomCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 50, SCREEN_WIDTH, (SCREEN_WIDTH-60)/3 + 30) collectionViewLayout:BlayOut];
    _bottomCollectionView.backgroundColor = [UIColor whiteColor];
    _bottomCollectionView.dataSource = self;
    _bottomCollectionView.delegate = self;
    _bottomCollectionView.bounces = NO;
    _bottomCollectionView.scrollEnabled = NO;
    _bottomCollectionView.contentInset = UIEdgeInsetsMake(10, 10, 0, 10);
    [self.mainScr addSubview:_bottomCollectionView];
}


- (void)goToTheme
{
    _TC = [[OPThemeController alloc]init];
    [self.navigationController pushViewController:_TC animated:YES];
}

- (void)requestUpData
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    [OPRequesterManager requestWithType:GET urlString:@"http://api.breadtrip.com/destination/index_places/3/" parDic:parDic finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        
        [_europeDataArray removeAllObjects];
        
        for (NSDictionary *countryDic in dic[@"data"]) {
            _mainEuropeModel = [[MainEuropeModel alloc]init];
            [_mainEuropeModel setValuesForKeysWithDictionary:countryDic];
            [self.europeDataArray addObject:_mainEuropeModel];
            
            [_dataBase executeUpdate:@"INSERT INTO MAINEROUP(cover_s,cover_route_map_cover,name,countryId,visited_count,wish_to_go_count) VALUES(?,?,?,?,?,?)",_mainEuropeModel.cover_s,_mainEuropeModel.cover_route_map_cover,_mainEuropeModel.name, _mainEuropeModel.countryId, [NSNumber numberWithInteger:_mainEuropeModel.visited_count] ,[NSNumber numberWithInteger:_mainEuropeModel.wish_to_go_count]];
            
        }
        _europeNameLabel.text = dic[@"title"];
        [_topCollectionView reloadData];
        [_mainScr.header endRefreshing];
        
        UILabel *ESTlabel = [[UILabel alloc]initWithFrame:CGRectMake(0, (SCREEN_WIDTH-60)/3 + 115, SCREEN_WIDTH, 20)];
        ESTlabel.text = @"感受异域风情";
        ESTlabel.textAlignment = NSTextAlignmentCenter;
        ESTlabel.font = [UIFont systemFontOfSize:10];
        ESTlabel.textColor = [UIColor grayColor];
        [self.mainScr addSubview:ESTlabel];
        
          [_topCollectionView reloadData];
        
    } error:^(NSError *error) {
        NSLog(@"----------欧洲国家数据请求失败---------");
    }];
}

- (void)requestDownData
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    [OPRequesterManager requestWithType:GET urlString:@"http://mapi.mafengwo.cn/travelguide/discovery/home?device_type=android&app_ver=6.1.0&open_udid=ac%3Af7%3Af3%3Aa4%3A73%3Acd&oauth_signature=nKbIQ2euJfOoN6jQhUHQxLcAkN8%3D&screen_height=1280&oauth_signature_method=HMAC-SHA1&oauth_consumer_key=5&oauth_version=1.0&oauth_timestamp=1445931750&oauth_nonce=107680a6-6251-47c6-bf97-2e1a06a432ee&hardware_model=MI+2S&device_id=ac%3Af7%3Af3%3Aa4%3A73%3Acd&sys_ver=5.0.2&channel_id=SLL&screen_width=720&oauth_token=0_0969044fd4edf59957f4a39bce9200c6&screen_scale=2.0&mfwsdk_ver=20140507&x_auth_mode=client_auth&app_code=com.mfw.roadbook" parDic:parDic finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSArray *listArray = dic[@"data"][@"list"];
        NSDictionary *themeDic = listArray[2];
        
        OPMainOptionalModel *themeModel = [[OPMainOptionalModel alloc]init];
        [themeModel setValuesForKeysWithDictionary:themeDic];

            [_TtitleButton setTitle:themeModel.title forState:UIControlStateNormal];
            _TStitleLabel.text = themeModel.sub_title;
        
        
        for (NSDictionary *listDic in themeDic[@"list"]) {
            _mainThemeModel = [[MainThemeModel alloc]init];
            [_mainThemeModel setValuesForKeysWithDictionary:listDic];
            [self.themeDataArray addObject:_mainThemeModel];
            
            
                        [_dataBase executeUpdate:@"INSERT INTO MAINTHEME(img_url,jump_url,sub_title,title) VALUES(?,?,?,?)",_mainThemeModel.img_url,_mainThemeModel.jump_url,_mainThemeModel.sub_title,_mainThemeModel.title];
            
            
        }
      
        [_bottomCollectionView reloadData];
    
    } error:^(NSError *error) {
        NSLog(@"OPMainOptionalController 数据请求失败");
    }];
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == _topCollectionView) {
      return  _europeDataArray.count;
    }else
    {
    return _themeDataArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _topCollectionView) {
        MainEuropeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"topCollection" forIndexPath:indexPath];
        [cell setConfigureModel:_europeDataArray[indexPath.item]];
        return cell;
    }else
    {
        MainThemeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"bottomCollection" forIndexPath:indexPath];
        [cell setConfigureModel:_themeDataArray[indexPath.item]];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _topCollectionView) {
        OPCountryController *CC = [[OPCountryController alloc]init];
        CC.model = _europeDataArray[indexPath.item] ;
        [self.navigationController pushViewController:CC animated:YES];
    }else{
        ThemeDetailController *TDC = [[ThemeDetailController alloc]init];
        TDC.naviTitle = [_themeDataArray[indexPath.item] title];
        TDC.url = [_themeDataArray[indexPath.item] jump_url];
        TDC.img_url = [_themeDataArray[indexPath.item] img_url];
        [self.navigationController pushViewController:TDC animated:YES];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
